package com.jy.datapipeline.importserver.support;

import cn.hutool.core.util.ObjectUtil;
import com.jy.datapipeline.common.constants.ExpConstants;
import com.jy.datapipeline.common.constants.FormatConstants;
import com.jy.datapipeline.common.constants.PrefixConstants;
import com.jy.datapipeline.common.exception.GlobalException;
import com.jy.datapipeline.common.util.DateTimeUtil;
import com.jy.datapipeline.common.util.SnowFlakeUtil;
import com.jy.datapipeline.common.util.StringUtil;
import com.jy.datapipeline.importserver.common.constants.TaskConstant;
import com.jy.datapipeline.importserver.common.dto.TaskTemplateDto;
import com.jy.datapipeline.importserver.common.enums.impl.DataIntervalUnitEnum;
import com.jy.datapipeline.importserver.common.enums.impl.ReturnEnum;
import com.jy.datapipeline.importserver.common.enums.impl.TaskStatusEnum;
import com.jy.datapipeline.importserver.common.enums.impl.TaskTypeEnum;
import com.jy.datapipeline.importserver.entity.ImportTask;
import com.mysql.cj.util.StringUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @类名 ImportTaskSupport
 * @作者 白条君
 * @创建日期 2023/8/24 16:46
 * @版本 1.0
 */
public class ImportTaskSupport {

    public static void configImportTask(ImportTask importTask, TaskTemplateDto taskTemplateDto) {
        //配置任务的子任务重试时间间隔和次数
        ImportTaskSupport.configSubtaskRetryPlant(importTask);

        //手动执行状态
        importTask.setTaskStatus(String.valueOf(TaskStatusEnum.NOT_START.getCode()));

        //自动执行状态
        Date nextStartTime;
        String cornTab;
        if (Integer.valueOf(importTask.getTaskType()).equals(TaskTypeEnum.AUTO_EXECUTE.getCode())) {
            Integer value = importTask.getDataIntervalValue();
            String unit = importTask.getDataIntervalUnit();
            nextStartTime = importTask.getNextStartTime();
            cornTab = importTask.getCornTab();
            if (ObjectUtil.isNull(value) || StringUtils.isNullOrEmpty(unit) || ObjectUtil.isNull(nextStartTime) || StringUtils.isNullOrEmpty(cornTab)) {
                throw new GlobalException(ReturnEnum.PARAM_ERROR.getCode(), ExpConstants.PARAMS_EXP);
            }

            //自动执行状态
            importTask.setTaskStatus(String.valueOf(TaskStatusEnum.RUNNING.getCode()));
        }

        String taskId = StringUtil.concat(new StringBuffer(), PrefixConstants.TASK_PREFIX, "_", SnowFlakeUtil.getNextId().toString());
        importTask.setTaskId(taskId);

        importTask.setUpdateTime(DateTimeUtil.getNow());
        String startTime = taskTemplateDto.getNextStartTime();
        importTask.setNextStartTime(DateTimeUtil.parseDate(startTime, FormatConstants.DATETIME_FORMAT));
    }

    public static void configSubtaskRetryPlant(ImportTask importTask) {
        Integer trySubtaskLoadInterval = importTask.getTrySubtaskLoadInterval();
        Integer trySubtaskLoadCount = importTask.getTrySubtaskLoadCount();
        Map<String, Integer> plant = ImportTaskSupport.getSubtaskRetryPlant(importTask.getDataIntervalUnit(), trySubtaskLoadInterval, trySubtaskLoadCount);
        if (plant.size() > 0) {
            Integer interval = plant.get(TaskConstant.LOAD_INTERVAL_KEY);
            if (interval != null && interval != 0) {
                importTask.setTrySubtaskLoadInterval(interval);
            }
            Integer count = plant.get(TaskConstant.LOAD_COUNT_KEY);
            if (count != null && count != 0) {
                importTask.setTrySubtaskLoadCount(count);
            }
        }
    }

    private static Map<String, Integer> getSubtaskRetryPlant(String dataIntervalUnit, Integer loadInterval, Integer loadCount) {
        Map<String, Integer> res = new HashMap<>();
        /**
         * 默认情况下
         * 月，重试时间间隔1小时；
         * 日，重试时间间隔20分钟；
         * 时，重试时间间隔10分钟；
         * 分，重试时间间隔5分钟；
         */
        if (loadInterval == null || loadInterval == 0) {
            int intervalUnit = Integer.parseInt(dataIntervalUnit);
            if (DataIntervalUnitEnum.MONTH.getCode() == intervalUnit) {
                res.put(TaskConstant.LOAD_INTERVAL_KEY, 60);
            } else if (DataIntervalUnitEnum.DAY.getCode() == intervalUnit) {
                res.put(TaskConstant.LOAD_INTERVAL_KEY, 20);
            } else if (DataIntervalUnitEnum.HOUR.getCode() == intervalUnit) {
                res.put(TaskConstant.LOAD_INTERVAL_KEY, 10);
            } else if (DataIntervalUnitEnum.MINUTES.getCode() == intervalUnit) {
                res.put(TaskConstant.LOAD_INTERVAL_KEY, 5);
            }
        }

        //默认重试次数为6次
        if (loadCount == null || loadCount == 0) {
            res.put(TaskConstant.LOAD_COUNT_KEY, 6);
        }
        return res;
    }
}
